package com.dm.utils;


import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MapBean {
    public static  <T> T mapToBean(Map<String, Object> map ,Class<?> clazz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        T obj = (T)clazz.getDeclaredConstructor().newInstance();
        try {
            BeanInfo bean = Introspector.getBeanInfo(clazz);
            PropertyDescriptor[] propertyDescriptorArr = bean.getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptorArr.length; i++) {
                PropertyDescriptor propertyDescriptor = propertyDescriptorArr[i];
                String name = propertyDescriptor.getName();
                if(map.containsKey(name)) {
                    Object value = map.get(name);
                    if("null".equals(value)) {
                        value = null;
                    }
                    Object[] objArr = new Object[propertyDescriptorArr.length];
                    objArr[i] = value;
                    try {
                        propertyDescriptor.getWriteMethod().invoke(obj, objArr[i]);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }

            }
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }
        return obj;
    }

    /**
     * @Title: beanToMap
     * @Description: 实体类转map集合
     * @param: @param clazz
     * @param: @return
     * @param: @throws Exception
     * @return: Map<String,Object>
     * @author: GXB
     * @throws
     */
    public static Map<String, Object> beanToMap(Class<?> clazz) throws Exception{
        Map<String, Object> map = new HashMap<>();
        BeanInfo bean = Introspector.getBeanInfo(clazz);
        PropertyDescriptor[] propertyDescriptorArr = bean.getPropertyDescriptors();
        for (int i = 0; i < propertyDescriptorArr.length; i++) {
            PropertyDescriptor propertyDescriptor = propertyDescriptorArr[i];
            String name = propertyDescriptor.getName();
            Method getter = propertyDescriptor.getReadMethod();
            Object val = getter.invoke(clazz);
            map.put(name, val.toString());
        }
        return map;
    }
}
